import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { NavBar, Toast } from 'antd-mobile';
import { motion, AnimatePresence } from 'framer-motion';
import axios from '../../axios';
import './Com/Red.css';

const Red: React.FC = () => {
  const navigate = useNavigate();
  const [showRedPacket, setShowRedPacket] = useState(false);
  const [isOpening, setIsOpening] = useState(false);
  const [isOpened, setIsOpened] = useState(false);
  const [amount, setAmount] = useState(0);
  const [showAmount, setShowAmount] = useState(false);
  const [particles, setParticles] = useState<Array<{id: number, x: number, y: number}>>([]);
  const [coins, setCoins] = useState<Array<{id: number, velocityX: number, velocityY: number, delay: number}>>([]);
  const [hasReceived, setHasReceived] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleBack = () => {
    navigate('/app/my');
  };

  // 检查24小时内是否已经领取过红包
  const checkRecentlyReceived = () => {
    const redPacketData = localStorage.getItem('redPacketData'); // 获取本地存储的红包数据
    if (!redPacketData) {
      return false;
    }
    
    try {
      const data = JSON.parse(redPacketData);
      const now = new Date().getTime();
      
      // 检查是否过期（24小时）
      if (now - data.timestamp > 24 * 60 * 60 * 1000) {
        localStorage.removeItem('redPacketData');
        return false;
      }
      
      return true;
    } catch {
      localStorage.removeItem('redPacketData');
      return false;
    }
  };

  // 添加优惠券到用户数据
  const addCouponToUser = async (couponAmount: number) => {
    try {
      const yonghuId = localStorage.getItem('yonghuId');
      if (!yonghuId) {
        Toast.show('请先登录');
        return false;
      }

      const couponData = {
        id: `RPK${Date.now()}`,
        name: '天天领红包',
        type: '红包',
        discount: couponAmount,
        minAmount: 0,
        category: '全场通用',
        startTime: new Date().toISOString(),
        endTime: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
        description: '天天领红包获得的优惠券'
      };

      const response = await axios.post(`http://localhost:3000/hy/yonghu/${yonghuId}/coupons`, couponData);
      
      if (response.data.code === 200) {
        // 记录领取时间戳
        const redPacketRecord = {
          timestamp: new Date().getTime(),
          amount: couponAmount,
          couponId: couponData.id
        };
        localStorage.setItem('redPacketData', JSON.stringify(redPacketRecord));
        return true;
      } else {
        Toast.show('优惠券添加失败');
        return false;
      }
    } catch (error) {
      console.error('添加优惠券失败:', error);
      Toast.show('网络错误，请重试');
      return false;
    }
  };

  useEffect(() => {
    // 页面加载时延迟显示红包
    const timer = setTimeout(() => {
      setShowRedPacket(true);
    }, 500);

    // 检查24小时内是否已经领取过红包
    setHasReceived(checkRecentlyReceived());

    return () => clearTimeout(timer);
  }, []);

  const generateRandomAmount = () => {
    // 80% 概率获得 0.1-2.0 元红包，20% 概率获得 0 元
    const random = Math.random();
    if (random < 0.8) {
      return Math.floor((Math.random() * 19 + 1) * 10) / 100;
    } else {
      return 0;
    }
  };

  const handleOpenRedPacket = async () => {
    // 检查24小时内是否已经领取过红包
    if (hasReceived) {
      Toast.show(`您已领取过红包，明天再来！`);
      return;
    }

    setIsOpening(true);
    setLoading(true);
    
    // 生成随机金额
    const randomAmount = generateRandomAmount();
    setAmount(randomAmount);
    
    // 创建粒子动画
    const newParticles = Array.from({ length: 20 }, (_, i) => ({
      id: i,
      x: Math.random() * 300,
      y: Math.random() * 200
    }));
    setParticles(newParticles);
    
    // 创建金币爆炸特效
    const newCoins = Array.from({ length: 20 }, (_, i) => {
      const angle = (Math.PI * 2 * i) / 20 + (Math.random() - 0.5) * 0.5;
      const distance = 150 + Math.random() * 200;
      const velocityX = Math.cos(angle) * distance;
      const velocityY = Math.sin(angle) * distance;
      
      return {
        id: i,
        velocityX,
        velocityY,
        delay: Math.random() * 0.3
      };
    });
    setCoins(newCoins);
    
    // 延迟显示金额并添加优惠券
    setTimeout(async () => {
      setIsOpened(true);
      setShowAmount(true);
      
      // 如果金额大于0，添加优惠券
      if (randomAmount > 0) {
        const success = await addCouponToUser(randomAmount);
        if (success) {
          setHasReceived(true);
          Toast.show('红包已领取，优惠券已添加到您的账户！');
        }
      } else {
        Toast.show('很遗憾，红包空了，明天再来试试吧！');
      }
      
      setLoading(false);
      
      // 清除粒子和金币
      setTimeout(() => {
        setParticles([]);
        setCoins([]);
      }, 4000);
    }, 1000);
  };

  return (
    <div className="red-container">
      <NavBar onBack={handleBack} back="返回">
        天天领红包
      </NavBar>
      
      <div className="red-content">
        <div className="red-background">
          {/* 红包动画 */}
          <AnimatePresence>
            {showRedPacket && !isOpened && (
              <motion.div
                className="red-packet-container"
                initial={{ scale: 0, y: -100, opacity: 0 }}
                animate={{ scale: 1, y: 0, opacity: 1 }}
                exit={{ scale: 0, opacity: 0 }}
                transition={{ 
                  type: "spring", 
                  stiffness: 260, 
                  damping: 20,
                  duration: 0.8
                }}
              >
                <motion.div
                  className={`red-packet ${isOpening ? 'opening' : ''} ${hasReceived ? 'disabled' : ''}`}
                  onClick={!hasReceived && !loading ? handleOpenRedPacket : undefined}
                  whileHover={!hasReceived && !loading ? { scale: 1.05 } : {}}
                  whileTap={!hasReceived && !loading ? { scale: 0.95 } : {}}
                  animate={isOpening ? { 
                    rotateY: [0, 180, 360],
                    scale: [1, 1.2, 1]
                  } : {}}
                  transition={{ duration: 1 }}
                >
                  <div className="red-packet-top">
                    <div className="red-packet-bow"></div>
                  </div>
                  <div className="red-packet-body">
                    <div className="red-packet-text">
                      恭喜发财
                    </div>
                    <div className="red-packet-subtitle">
                      {hasReceived ? '今日已领取' : loading ? '正在开启...' : '点击开启红包'}
                    </div>
                  </div>
                </motion.div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 粒子效果 */}
          <AnimatePresence>
            {particles.map(particle => (
              <motion.div
                key={particle.id}
                className="particle"
                initial={{ x: 150, y: 200, opacity: 1, scale: 1 }}
                animate={{ 
                  x: particle.x, 
                  y: particle.y, 
                  opacity: 0,
                  scale: 0
                }}
                transition={{ 
                  duration: 2,
                  ease: "easeOut"
                }}
              />
            ))}
          </AnimatePresence>

          {/* 额外的粒子效果 */}
          {isOpened && (
            <div className="extra-particles">
              {Array.from({ length: 30 }).map((_, i) => (
                <motion.div
                  key={`extra-${i}`}
                  className="extra-particle"
                  initial={{ 
                    x: 150, 
                    y: 200, 
                    opacity: 1,
                    scale: 1
                  }}
                  animate={{ 
                    x: Math.random() * 400 - 50, 
                    y: Math.random() * 600 - 100,
                    opacity: 0,
                    scale: 0
                  }}
                  transition={{ 
                    duration: 3,
                    delay: i * 0.1,
                    ease: "easeOut"
                  }}
                />
              ))}
            </div>
          )}

          {/* 金币爆炸特效 */}
          <AnimatePresence>
            {coins.map(coin => (
              <motion.div
                key={`coin-${coin.id}`}
                className="falling-coin"
                initial={{ 
                  x: '50%',
                  y: '40%',
                  opacity: 1,
                  scale: Math.random() * 0.4 + 0.8,
                  rotate: 0
                }}
                animate={{ 
                  x: `calc(50% + ${coin.velocityX}px)`,
                  y: `calc(40% + ${coin.velocityY}px + 200px)`,
                  rotate: 720 + Math.random() * 720,
                  opacity: [1, 1, 0.8, 0.6, 0],
                  scale: [null, 1.2, 1, 0.8, 0.6]
                }}
                transition={{ 
                  duration: 2.5 + Math.random() * 1,
                  delay: coin.delay,
                  ease: "easeOut",
                  y: {
                    ease: "easeIn",
                    duration: 3
                  }
                }}
              >
                💰
              </motion.div>
            ))}
          </AnimatePresence>

          {/* 金额显示 */}
          <AnimatePresence>
            {showAmount && (
              <motion.div
                className="amount-display"
                initial={{ scale: 0, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ 
                  type: "spring", 
                  stiffness: 300, 
                  damping: 30,
                  delay: 0.5
                }}
              >
                <motion.div
                  className="amount-card"
                  initial={{ y: 50 }}
                  animate={{ y: 0 }}
                  transition={{ delay: 0.8 }}
                >
                  <div className="amount-title">恭喜获得</div>
                  <motion.div
                    className="amount-value"
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    transition={{ 
                      type: "spring", 
                      stiffness: 400, 
                      damping: 10,
                      delay: 1
                    }}
                  >
                    ¥{amount.toFixed(2)}
                  </motion.div>
                  <div className="amount-subtitle">
                    {amount === 0 ? '再接再厉！' : '红包已到账'}
                  </div>
                </motion.div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
};

export default Red;